package com.example.alternateThread.park;

import java.util.concurrent.locks.LockSupport;

// 特别要注意：调用了LockSupport.unpark(thread);后thread的LockSupport.park();就失效了，因此不能用类似于ReentrantLock的形式
public class AlternateThread {
    // 这里要考虑到循环依赖的情况，因此将提前用到的线程先用static类型的变量保存下来！！！
    static Thread thread1 = null;
    static Thread thread2 = null;
    static Thread thread3 = null;

    public static void print(char ch, Thread next) {
        for (int i = 0; i < 5; i++) {
            // 当前线程先睡
            LockSupport.park();
            // 打印当前线程内容
            System.out.print(ch);
            // 再唤醒其他线程
            LockSupport.unpark(next);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        thread1 = new Thread(() -> {
            print('A', thread2);
        });
        thread2 = new Thread(() -> {
            print('B', thread3);
        });
        thread3 = new Thread(() -> {
            print('C', thread1);
        });
        // 所有线程都会先睡
        thread1.start();
        thread2.start();
        thread3.start();

        // 创建一个事件的驱动者先把线程1唤醒
        LockSupport.unpark(thread1);

    }
}

